from openpyxl import Workbook, load_workbook
import openpyxl
import openpyxl.styles as sty
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
from django.shortcuts import render
from . import models
from user.views import getColl
from django.http import JsonResponse, HttpResponse
from rest_framework.views import APIView
from rest_framework import exceptions
from rest_framework import serializers
from rest_framework.pagination import CursorPagination, LimitOffsetPagination
# from rest_framework.pagination import LimitOffsetPagination
import json

from Config.views import getconfigOBJ
# 根据三级定位的id获取对应商品 包括分页


class goodsSer(serializers.ModelSerializer):
    price = serializers.CharField(source='getPrice')

    class Meta:
        model = models.GoodsBase
        fields = ['id', 'title', 'src', 'price']
        # depth = 1


class MyCursorPagination(CursorPagination):
    def __init__(self, *args, **kwargs):
        self.page_size = int(args[0])

    cursor_query_param = 'cursor'
    ordering = 'id'  # 重写要排序的字段

# 通用 获取定位商品数据


def GoodsPage(name, page, request, self, Goods, p_size):
    pg = MyCursorPagination(p_size, self)
    pg_list = pg.paginate_queryset(queryset=Goods, request=request, view=self)
    Goods = pg_list
    GoodsList = goodsSer(instance=Goods, many=True).data
    return pg.get_paginated_response(GoodsList).data


class locaSer(serializers.ModelSerializer):
    class Meta:
        model = models.GoodsLocation3
        fields = ['id', 'msg', 'config']


def getGoods(name, page, request, self, p_size):
    ret = {}
    # try:
    ser = models.GoodsLocation3.objects.get(name=name)
    print(name)
    config = locaSer(instance=ser, many=False).data
    if config['config']:
        config['config'] = json.loads(config['config'])  # 对字符串对象进行转码
    Goods = models.GoodsGather.objects.get(GoodsBase=ser).goodsList.all()
    if page:
        GoodsList = GoodsPage(name, page, request, self, Goods, p_size)
    else:
        GoodsList = goodsSer(instance=Goods, many=True).data
    ret = {'GoodsList': GoodsList, 'config': config}
    # except:
    #     return None
    return ret


class locateGoods(APIView):
    def get(self, request, *args, **kwargs):
        dicS = {}
        try:
            name = request.GET['name']
        except:
            name = None
        try:
            page = request.GET['page']
        except:
            page = None
        # print("cursor=",cursor)
        ser = getGoods(name, page, request, self, page)
        if ser:
            dicS = {'config': ser['config'], 'GoodsList': ser['GoodsList']}
        return JsonResponse(dicS)

# 获取商品详情

class DetailedSer(serializers.ModelSerializer):
    class Meta:
        model = models.GoodesDetailed
        exclude = ["id", "star_time", "last_time", "shelves", "isDelete"]
        depth = 1


class Products(APIView):
    def get(self, request, *args, **kwargs):
        '''
        接受的list里面的ID是 specifications 表ID 既商品套餐显示的时候ID
        '''
        id = -1
        Goods = None
        
        # models.GoodesDetailed.objects.all().delete()
        # models.GoodsColor.objects.all().delete()
        # models.specifications.objects.all().delete()
        # models.Goodspackage.objects.all().delete()
        # ret = {}
        # return JsonResponse(ret)

        try:
            id = request.GET['id']
            base = models.GoodsBase.objects.get(id=id)
            Goods = models.GoodesDetailed.objects.get(GoodsBase=base)
        except:
            pass
        GoodsData = DetailedSer(instance=Goods, many=False).data
        GoodsData['imgList'] = json.loads(Goods.imgList)
        # 获取颜色 和 套餐
        color = models.GoodsColor.objects.filter(Goods=Goods)
        spec = models.specifications.objects.filter(Goods=Goods)
        pack = models.Goodspackage.objects.filter(Goods=Goods)
        # 根据颜色id 获取搭配数据
        GoodsData['havaCategory'] = [
            {
                "category": "颜色分类",
                "list": GoodsColorSer(instance=color, many=True).data
            },
             {
                "category": "套餐",
                "list": specificationsSer(instance=spec, many=True).data
            },
        ]
        GoodsData['pack'] = GoodspackageSer(instance=pack, many=True).data
        GoodsData['Coll'] =  True if getColl(request,base.id) else False
        return JsonResponse(GoodsData)


class GoodsColorSer(serializers.ModelSerializer):
    class Meta:
        model = models.GoodsColor
        fields = ['title','id']


class specificationsSer(serializers.ModelSerializer):
    class Meta:
        model = models.specifications
        fields = ['title','id']


class GoodspackageSer(serializers.ModelSerializer):
    class Meta:
        model = models.Goodspackage
        exclude = ['Goods']


# H5 分类数据


class LeveSer(serializers.ModelSerializer):
    class Meta:
        model = models.GoodsBase
        fields = ['id', 'title', 'src', 'price']
# class getLeve(APIView):
#     def get(self, request, *args, **kwargs):
#         ser = models.GoodsLocation3.objects.all()
#         return JsonResponse(dicS)


# class contentRelateField(serializers.RelatedField):
#     def to_representation(self, value):
#         value = '1'
#         return value
# class GoodsLocation3Ser(serializers.ModelSerializer):
#     content = contentRelateField(read_only=True)
#     class Meta:
#         model = models.GoodsLocation3
#         fields = ['id','name','content']
#         # depth = 2
class h5Class(APIView):
    def get(self, request, *args, **kwargs):
        ret = {}
        listData = []
        lo1 = models.ClassLevel2.objects.all()
        for i in lo1:
            lo2 = models.ClassLevel3.objects.filter(ClassID=i.id)
            content = []
            for j in lo2:
                content.append({'cid': j.id, 'cname': j.name, 'thumb': j.img})
            listData.append({'id': i.id, 'name': i.name, 'content': content})
        ret['list'] = listData
        return JsonResponse(ret, safe=False)


class CLASS3SER(serializers.ModelSerializer):
    class Meta:
        model = models.ClassLevel3
        fields = ['id', 'name', 'ClassID']


class CLASS2SER(serializers.ModelSerializer):
    class Meta:
        model = models.ClassLevel2
        fields = ['id', 'name', 'ClassID']


class CLASS1SER(serializers.ModelSerializer):
    class Meta:
        model = models.ClassLevel1
        fields = ['id', 'name']


class PCClass(APIView):
    def get(self, request, *args, **kwargs):
        ret = {}
        listData = []
        C1 = models.ClassLevel1.objects.all()
        for f in C1:
            C2 = models.ClassLevel2.objects.filter(ClassID=f.id)
            SJ2 = []
            for i in C2:
                C3 = models.ClassLevel3.objects.filter(ClassID=i.id)
                SJ3 = []
                for j in C3:
                    SJ3.append({'id': j.id, 'name': j.name})
                SJ2.append({'id': i.id, 'name': i.name, 'list': SJ3})
            listData.append({'id': f.id, 'name': f.name, 'list': SJ2})
        ret['list'] = listData
        return JsonResponse(ret, safe=False)


class operationGoods(APIView):
    def post(self, request, *args, **kwargs):
        ret = {}
        ALLDATA = Convert.xls2json()
        for excel in ALLDATA:
            # 商品基础信息
            Base = {
                'title': excel['title'],
                'price': excel['price'],
                'src': excel['src']
            }
            GoodsBase = models.GoodsBase.objects.create(**Base)

            # 商品详细信息
            Detailed = {
                'title': excel['title2'],
                'imgList': excel['imgList'],
                'richText': excel['richText'],
                'shelves': excel['shelves'],
            }
            Detailed['GoodsBase'] = GoodsBase
            GoodesDetailed = models.GoodesDetailed.objects.create(**Detailed)

            # 商品分类与服务类型
            serviceList = json.loads(excel['service'])
            ClassList = json.loads(excel['ClassList'])
            typeData = {
                'ClassList': ClassList,
                'service': serviceList
            }
            for i in typeData['ClassList']:
                ClassLevel3 = models.ClassLevel3.objects.get(id=i)
                GoodesDetailed.goodsClass.add(ClassLevel3)
            for i in typeData['service']:
                GoodesService = models.GoodesService.objects.get(id=i)
                GoodesDetailed.Service.add(GoodesService)
        return JsonResponse(ret, safe=False)
        # 颜色分类
        GoodsColor = [
            {
                'title': '1',
                'src': '1',
            },
            {
                'title': '1',
                'src': '1',
            },
            {
                'title': '1',
                'src': '1',
            }
        ]
        ColorList = []
        for i in GoodsColor:
            i['Goods'] = GoodesDetailed
            GoodsColorOBJ = models.GoodsColor.objects.create(**i)
            ColorList.append(GoodsColorOBJ)
        # 套餐
        specifications = [
            {
                'title': '1',
                'src': '1',
            },
            {
                'title': '1',
                'src': '1',
            },
            {
                'title': '1',
                'src': '1',
            }
        ]
        SpeList = []
        for i in specifications:
            i['Goods'] = GoodesDetailed
            SpeOBJ = models.specifications.objects.create(**i)
            SpeList.append(SpeOBJ)
        # 套餐 和颜色 搭配价格
        Goodspackage = [
            {
                'price': 'co',
                'inventory': 'co',
            }, {
                'price': 'co',
                'inventory': 'co',
            }, {
                'price': 'co',
                'inventory': 'co',
            }, {
                'price': 'co',
                'inventory': 'co',
            }, {
                'price': 'co',
                'inventory': 'co',
            }, {
                'price': 'co',
                'inventory': 'co',
            }, {
                'price': 'co',
                'inventory': 'co',
            }, {
                'price': 'co',
                'inventory': 'co',
            }, {
                'price': 'co',
                'inventory': 'co',
            }
        ]
        # for i in ColorList:

        # Goodspackage = {
        #     'price': 1991,
        #     'inventory': 1991,
        # }
        # Goodspackage['colorID'] = GoodsColorOBJ
        # Goodspackage['speID'] = specificationsOBJ
        # models.Goodspackage.objects.create(**Goodspackage)

        return JsonResponse(ret, safe=False)


class Convert():
    @staticmethod
    def json2xls(fileName):
        wb1 = Workbook()
        sheet = wb1.active
        listHead = []
        data = json.load(open(fileName+".json", "r", encoding="utf-8"))
        for c, i in enumerate(data[0].keys()):
            sheet.cell(row=1, column=c+1, value=i)
            listHead.append(i)
        for r, i in enumerate(data):
            row = r+2
            for c, d in enumerate(listHead):
                sheet.cell(row=row, column=c+1, value=i.get(d, ""))

        wb1.save(fileName+".xlsx")

    @staticmethod
    def xls2json():
        fileName = "C:\mi\Django\EV30DB\数据"
        wb = load_workbook(fileName+".xlsx")
        ws = wb["商品数据"]
        r = ws.max_row
        c = ws.max_column
        list_key = []
        jsonLine = []
        for col in range(1, c+1):
            list_key.append(ws.cell(row=1, column=col).value)
        for row in range(2, r+1):
            dict_v = {}
            for col in range(1, c+1):
                dict_v[list_key[col-1]] = ws.cell(row=row, column=col).value
            jsonLine.append(dict_v)
        return jsonLine
        # json.dump(jsonLine,open(fileName+".json","w",encoding="utf-8"))

# class MyCursorPagination(CursorPagination):
#     def __init__(self, *args, **kwargs):
#         self.page_size =int(args[0])
#     cursor_query_param = 'cursor'
#     ordering = 'id'  # 重写要排序的字段
#     #自定义分页类
# 自定义分页类2


class MyLimitOffsetPagination(LimitOffsetPagination):
    # 默认显示的个数
    def __init__(self, *args, **kwargs):
        self.default_limit = int(args[0])
        self.limit = 1
    # 当前的位置
    offset_query_param = "offset"
    # 通过limit改变默认显示的个数
    limit_query_param = "limit"
    # 一页最多显示的个数
    max_limit = 30


class goodsDeSer(serializers.ModelSerializer):
    class Meta:
        model = models.GoodesDetailed
        fields = ['id', 'title', 'GoodsBase', 'inventory', 'price', 'sales']
        depth = 1


class screening(APIView):
    def get(self, request, *args, **kwargs):
        ret = {}
        # 获取所有数据
        pageSize = 5  # 一页多少条数据
        c1 = int(request.GET['c1'])
        c2 = int(request.GET['c2'])
        c3 = int(request.GET['c3'])

        idList = []
        if c3 != 0:
            idList.append(c3)
        elif c2 != 0:
            c3List = models.ClassLevel3.objects.filter(ClassID=c2)
            for i in c3List:
                idList.append(i.id)
        goods = models.GoodesDetailed.objects.filter(goodsClass__in=idList)
        lenGoods = len(goods)
        # 排序
        try:
            filterIndex = int(request.GET['filterIndex'])
            orderList = ['-id', 'sales', '-price', 'price']
            if filterIndex >= 0 and filterIndex <= len(orderList)-1:
                goods = goods.order_by(orderList[filterIndex])
        except:
            pass

        # 创建分页对象
        pg = MyLimitOffsetPagination(pageSize)
        # 获取分页的数据
        page_roles = pg.paginate_queryset(
            queryset=goods, request=request, view=self)
        # 对数据进行序列化
        GoodsList = goodsDeSer(instance=page_roles, many=True).data
        ret['list'] = GoodsList

        ret['total'] = lenGoods
        ret['pageSize'] = pageSize
        # 0 5 10  15    10-6=4  4<5  15-6=9>5/
        offset = int(request.GET['offset'])+pageSize
        if offset < lenGoods or (offset - lenGoods) < pageSize:
            ret['offset'] = offset
            ret['isNext'] = False
        else:
            ret['offset'] = offset-pageSize
            ret['isNext'] = True

        return JsonResponse(ret, safe=False)
